import { useEffect, useRef } from 'react'
import './ResizeModal.scss'
import RemoveSvg from '@/svg/RemoveSvg'
import useStateRef from '@/hooks/useStateRef'
import imageLoadManager from '@/lib/imageLoadManager'
import { loadImageInfo } from '@/utils/loadVideo'
import { imageResize } from '@/lib/imageResize'
import { showLoading } from '@/utils/loading'
import CustomCanvas from '@/component/CustomCanvas'
import { useI18n } from '@/i18n'
interface Props {
  show: boolean
  onHide: () => void
  frameList: FrameInfo[]
  allFrameList: FrameInfo[]

  fps: number
  onUpdate: (frameList: FrameInfo[]) => void
}

const ResizeModal = ({
  show,
  onHide,
  frameList,
  fps,
  onUpdate,
  allFrameList,
}: Props) => {
  const { t } = useI18n()
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const imageFrameList = useRef<HTMLImageElement[]>([])
  const canvasCtx = useRef<CanvasRenderingContext2D | null>(null)
  const [canvasSize, setCanvasSize, canvasSizeRef] = useStateRef({
    width: 200,
    height: 200,
  })
  const [keepRatio, setKeepRatio] = useStateRef(true)
  const originSize = useRef({
    width: 200,
    height: 200,
  })
  useEffect(() => {
    if (!show) return
    const task = async () => {
      if (frameList.length != 0) {
        const info = await loadImageInfo(frameList[0].url)
        setCanvasSize({
          width: info.width,
          height: info.height,
        })
        canvasRef.current.width = info.width
        canvasRef.current.height = info.height
        originSize.current = { width: info.width, height: info.height }
      } else {
        setCanvasSize({ width: 200, height: 200 })
        canvasRef.current.width = 200
        canvasRef.current.height = 200
        originSize.current = { width: 200, height: 200 }
      }
    }
    task()
  }, [frameList, show])

  useEffect(() => {
    if (!show) {
      return
    }
    let isEnd = false
    const task = async () => {
      imageFrameList.current = await imageLoadManager.loadImageList(frameList)
      //   if (!play) {
      //     return
      //   }
      // 帧时间
      const frameTime = 1000 / fps
      let frame = 0
      let nowframeTime = 0
      let lastTime = 0
      canvasCtx.current = canvasRef.current.getContext('2d')
      canvasCtx.current.imageSmoothingEnabled = false
      const anim = (nowTime: number) => {
        const deltaTime = nowTime - lastTime
        lastTime = nowTime
        nowframeTime += deltaTime
        const addFrame = Math.floor(nowframeTime / frameTime)
        nowframeTime = nowframeTime % frameTime
        draw(frame)
        frame += addFrame
        if (frameList.length == 0) isEnd = true
        while (frame >= frameList.length && frameList.length != 0) {
          frame -= frameList.length
        }
        if (isEnd) return
        requestAnimationFrame(anim)
      }
      requestAnimationFrame(anim)
    }
    task()
    return () => {
      isEnd = true
    }
  }, [show, frameList, canvasSize])
  const draw = (frame = 0) => {
    if (frame < 0 || frame >= imageFrameList.current.length) {
      return
    }
    const ctx = canvasCtx.current
    if (!ctx) return
    const w = canvasSizeRef.current.width
    const h = canvasSizeRef.current.height
    ctx.clearRect(0, 0, w, h)
    if (frameList.length == 0) {
      return
    }
    const imageW = imageFrameList.current[frame].naturalWidth
    const imageH = imageFrameList.current[frame].naturalHeight
    ctx.drawImage(
      imageFrameList.current[frame],
      0,
      0,
      imageW,
      imageH,
      0,
      0,
      w,
      h
    )
  }
  const setSize = (width: number, height: number) => {
    setCanvasSize({ width, height })
    canvasRef.current.width = width
    canvasRef.current.height = height
  }

  async function onSave(): Promise<void> {
    const hideloading = showLoading()
    try {
      const res = await imageResize(
        allFrameList,
        canvasSize.width,
        canvasSize.height,
        (cur, len) => {
          hideloading.setProgress((cur / len) * 100)
        }
      )
      onUpdate(res)
    } catch (e) {
      console.error(e)
    } finally {
      hideloading()
    }
  }

  return (
    <div className="resize-modal-component">
      <div className={`resize-modal ${show ? 'show' : ''}`}>
        <div className="top">
          <div className="title">
            <span>{t('resize')}</span>
          </div>
          <ripple-button className="remove" onClick={onHide}>
            <RemoveSvg />
          </ripple-button>
        </div>
        <div className="center-box">
          <div className="canvas-view">
            <CustomCanvas className="canvas" ref={canvasRef}></CustomCanvas>
          </div>
          <div className="input-box">
            <div className="label">
              <label>{t('width')}</label>
            </div>
            <input
              type="number"
              onChange={(e) => {
                const value = parseInt(e.target.value)
                if (value > 0) {
                  let height = canvasSizeRef.current.height
                  if (keepRatio) {
                    height = Math.max(
                      Math.round(
                        (value * originSize.current.height) /
                          originSize.current.width
                      ),
                      1
                    )
                  }
                  setSize(value, height)
                }
              }}
              min={1}
              max={65536}
              className="input"
              value={canvasSize.width}></input>
          </div>
          <div className="input-box">
            <div className="label">
              <label>{t('height')}</label>
            </div>
            <input
              type="number"
              onChange={(e) => {
                const value = parseInt(e.target.value)
                if (value > 0) {
                  let width = canvasSizeRef.current.width
                  if (keepRatio) {
                    width = Math.max(
                      Math.round(
                        (value * originSize.current.width) /
                          originSize.current.height
                      ),
                      1
                    )
                  }
                  setSize(width, value)
                }
              }}
              min={1}
              max={65536}
              className="input"
              value={canvasSize.height}></input>
          </div>
          <div className="input-box">
            <div className="label">
              <label>{t('axisEqual')}</label>
            </div>
            <input
              type="checkbox"
              onChange={(e) => setKeepRatio(e.target.checked)}
              className="checkbox"
              checked={keepRatio}></input>
          </div>
        </div>
        <ripple-button
          style={{
            marginLeft: 'auto',
            background: 'var(--primary-color)',
            color: 'white',
            width: 'fit-content',
            padding: '8px 10px',
          }}
          onClick={onSave}>
          {t('saveChanges')}
        </ripple-button>
      </div>
      <div className={`mask ${show ? 'show' : ''}`} onClick={onHide}></div>
    </div>
  )
}

export default ResizeModal
